package com.lantian.teacher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantian.teacher.entity.EduSubject;
import com.lantian.teacher.entity.vo.OneSubject;
import com.lantian.teacher.entity.vo.TwoSubject;
import com.lantian.teacher.mapper.EduSubjectMapper;
import com.lantian.teacher.service.EduSubjectService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @name:
 * @description: 课程科目服务实现类
 * @author: meet
 * @create: 2020-05-01 14:35
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
    /**
     * 07版 excel 读取保存数据库
     *
     * @param file
     * @return
     */
    @Override
    public List<String> importEXCL(MultipartFile file) {

        List<String> msg = new ArrayList<>();
        try {
            //1、 获取文件流
            InputStream inputStream = file.getInputStream();
            //2、根据这流创建一个workBook
            Workbook workbook = new XSSFWorkbook(inputStream);
            //3、获取第一个Sheet
            Sheet sheet = workbook.getSheetAt(0);
            //4、根据这Sheet获取行数
            int lastRow = sheet.getLastRowNum();
            //如果sheet中一行数据都没有则返回-1，只有第一行有数据则返回0，最后有数据的行是第n行则返回 n-1；
            if (lastRow < 0) {
                msg.add("请填写数据");
                return msg;
            }
            //5、遍历行
            for (int rowNum = 0; rowNum <= lastRow; rowNum++) {
                Row row = sheet.getRow(rowNum);
                //6、获取每一行中第一列： 一级分类
                Cell cell = row.getCell(0);
                if (cell == null) {
                    msg.add("第" + rowNum + "行为空");
                    continue;
                } else {
                    row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                }
                //7、判断列是否存在，存在获取列的数据
                String cellValue = cell.getStringCellValue();
                if (StringUtils.isEmpty(cellValue)) {
                    msg.add("第" + rowNum + "行第1列数据为空");
                    continue;
                }
                EduSubject eduSubject = this.selectSubjectByName(cellValue);
                String pid = null;
                //8、把这个第一列中的数据（一级分类）保存到数据库中
                //9、在保存之前判断此一级分类是否存在，如果存在，不再添加；如果不存在再保存
                if (eduSubject == null) {
                    EduSubject subject = new EduSubject();
                    subject.setTitle(cellValue);
                    subject.setParentId("0");
                    subject.setSort(0);
                    baseMapper.insert(subject);
                    pid = subject.getId();
                } else {
                    pid = eduSubject.getId();
                }


                //10、再获取每一行的第二列
                Cell cell1 = row.getCell(1);
                if (cell1 == null) {
                    msg.add("第" + rowNum + "行，第2列为空");
                    continue;
                } else {
                    row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                }
                //11、判断第二列数据是否为空，获取第二列中的数据（二级分类）
                String cellValue1 = cell1.getStringCellValue();
                if (StringUtils.isEmpty(cellValue1)) {
                    msg.add("第" + rowNum + "行，第2列数据为空");
                    continue;
                }
                //12、判断此一级分类中是否存在此二级分类
                EduSubject eduSubject1 = this.selectSubjectByNameAndPid(cellValue1, pid);
                //13、如果此一级分类中有此二级分类：不保存

                //14、如果没有保存二级分类
                if (eduSubject1 == null) {
                    EduSubject subject = new EduSubject();
                    subject.setTitle(cellValue1);
                    subject.setParentId(pid);
                    subject.setSort(0);
                    baseMapper.insert(subject);
                }
            }

            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }

    private EduSubject selectSubjectByNameAndPid(String cellValue1, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", cellValue1);
        wrapper.eq("parent_id", pid);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 查询是否为一级分类
     * @param cellValue
     * @return
     */
    private EduSubject selectSubjectByName(String cellValue) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", cellValue);
        wrapper.eq("parent_id", 0);
        EduSubject eduSubject = baseMapper.selectOne(wrapper);
        return eduSubject;
    }

    /**
     * 获取课程树形列表
     *
     * @return
     */
    @Override
    public List<OneSubject> getTree() {

        ArrayList<OneSubject> subjectList = new ArrayList<>();
        // 2、获取一级分类的列表
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0);
        List<EduSubject> eduSubjectsList = baseMapper.selectList(wrapper);
        // 3、遍历一级分类的列表
        for (EduSubject eduSubjectOne : eduSubjectsList) {
            //4、一级分类的数据复制到OneSubject
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubjectOne, oneSubject);
            //5、根据每一个一级分类获取二级分类的列表
            QueryWrapper<EduSubject> twoWrapper = new QueryWrapper<>();
            twoWrapper.eq("parent_id", oneSubject.getId());
            List<EduSubject> eduSubjectsTwo = baseMapper.selectList(twoWrapper);
            // 6、遍历二级分类列表
            for (EduSubject eduSubjectTwo : eduSubjectsTwo) {
                //7、把二级分类对象复制到TwoSubject
                TwoSubject twoSubject = new TwoSubject();
                BeanUtils.copyProperties(eduSubjectTwo, twoSubject);
                //8、 把TwoSubject添加OneSubject 的children集合中
                oneSubject.getChildren().add(twoSubject);
            }
            // 9、把OneSubject添加到返回集合中
            subjectList.add(oneSubject);
        }

        return subjectList;
    }

    @Override
    public boolean deleteById(String id) {

        // 根据ID查询数据库中是否存在此ID为ParentId（二级分类）
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<EduSubject> eduSubjects = baseMapper.selectList(wrapper);

        if (eduSubjects.size() != 0) {
            return false;
        }
        int i = baseMapper.deleteById(id);
        return true;
    }

    @Override
    public boolean saveLevelOne(EduSubject eduSubject) {
        EduSubject subject = selectSubjectByName(eduSubject.getTitle());
        if (subject==null){
            eduSubject.setSort(0);
            int i = baseMapper.insert(eduSubject);
            return i==1;
        }else {
            return false;
        }
    }

    @Override
    public boolean saveLevelTwo(EduSubject subject) {

        //判断此一级分类中是否存在此二级分类的title
        EduSubject sub = this.selectSubjectByNameAndPid(subject.getTitle(), subject.getParentId());
        if(sub != null){
            //存在
            return false;
        }
        int insert = baseMapper.insert(subject);
        return insert == 1;
    }


}
